import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import cookie from 'js-cookie'
// 创建axios实例
const service = axios.create({
  baseURL: 'http://localhost:9001', // api的base_url
  timeout: 20000 // 请求超时时间
})

// http request 拦截器
service.interceptors.request.use(
  config => {
    //debugger
    if (cookie.get('front_token')) {
      config.headers['token'] = cookie.get('front_token');
    }
    return config
  },
  err => {
    return Promise.reject(err);
  })
// http response 拦截器
service.interceptors.response.use(

  response => {

    const res = response.data
    //30001是没传token，那说明没登陆，30002是传的token是错的，也要重新登陆
    if (res.code == 30001 || res.code == 30002 ) {
      Message({
        message: '请登陆才可以操作',
        type: 'error',
        duration: 5 * 1000
      })
      cookie.remove('front_token')
      cookie.remove('front_member')
      window.location.href="/login"
      return
    }else{
      if (res.code != 20000) {
        //25000：订单支付中，不做任何提示
        if(response.data.code != 25000) {
          Message({
            message: res.message || 'error',
            type: 'error',
            duration: 5 * 1000
          })
          return Promise.reject(error)
        }
      } else {
        return res;
      }
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  });
export default service
